Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Else if

Else if examples-2

here are some more if-else examples which hepls you to understand else if concept. Example 1 : Checking if a number is even or odd
Even or odd example in java
public class Main{ public static void main(String[] args) { int number = 10; if (number % 2 == 0) { System.out.println("The number is even."); } else { System.out.println("The number is odd."); } } }

Output

The number is even.
In this example, the given number is 10 and the value of 10 modulo 2 is 0. So the first if statement passed and given the output as The number is even. Example 2 : Checking if a string is empty
Empty string Checking in java
public class Main{ public static void main(String[] args) { String str = ""; if (str.isEmpty()) { System.out.println("The string is empty."); } else { System.out.println("The string is not empty."); } } }

Output

The string is empty.
In this example, str has an empty string. so the if statement passed and the output will be The string is empty. Example 3 : Checking if a file exists
File exists or not
public class Main{ public static void main(String[] args) { File file = new File("myfile.txt"); if (file.exists()) { System.out.println("The file exists."); } else { System.out.println("The file does not exist."); } } }

Output

The file exists.
In this example, the if condition checks for the file name in the path. If the file is present in the folder path it will give the output as The file exists.. If no it executes the else. Example 4 : Checking if a user is logged in
User login check example in java
public class Main{ public static void main(String[] args) { boolean isLoggedIn = true; if (isLoggedIn) { System.out.println("The user is logged in."); } else { System.out.println("The user is not logged in."); } } }

Output

The user is logged in.
In this example, we are checking the user login with a boolean datatype with a value false. so it does not executes the if and print the statment in else and the output will be The user is logged in. These are just a few examples of how the if-else statement can be used in Java. The if-else statement is a versatile and powerful tool that can be used to control the flow of execution of a program. It is an essential part of the Java programming language.

  📌TAGS

★If else condition ★java ★java if ★if else ★nested if else ★nested if ★conditional statements

Tutorials